const gid = document.getElementById('gid').value;
const cid = document.getElementById('cid').value;

// 显示登录弹窗
function showLoginModal() {

    const url = "{:url('/index/index/index')}";

    // 假设这里是发送验证码的API调用
    $.post(url,{type:login,gid:gid},function(info){
        console.log(info);return false;
        if(info.code==0) {
            layer.msg(info.msg,{time:2000});
            refreshCaptcha();
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            // 发送成功后开始倒计时
            startCountdown(button);
        }else{
            // 其他错误
            layer.msg(info.msg || '发送失败，请重试', {time: 2000});
        }
    })
    // document.getElementById('loginModal').style.display = 'block';
}

// 隐藏登录弹窗
function hideLoginModal() {

    document.getElementById('loginModal').style.display = 'none';
}

// 登录成功后显示悬浮球
function showFloatBall() {
    document.getElementById('floatBall').style.display = 'flex';
}

// 显示注册弹窗
function showRegisterModal() {
    document.getElementById('registerModal').style.display = 'block';
    document.getElementById('loginModal').style.display = 'none';
}

// 隐藏注册弹窗
function hideRegisterModal() {
    document.getElementById('registerModal').style.display = 'none';
    document.getElementById('loginModal').style.display = 'block';
}

// 显示忘记密码表单
function showForgotPassword() {
    showResetPasswordModal();
}

// 切换到手机号登录
function switchToPhoneLogin() {
    document.getElementById('accountLoginForm').style.display = 'none';
    document.getElementById('phoneLoginForm').style.display = 'block';
}

// 切换到账号登录
function switchToAccountLogin() {
    document.getElementById('phoneLoginForm').style.display = 'none';
    document.getElementById('accountLoginForm').style.display = 'block';
}

// 刷新图片验证码
function refreshCaptcha() {
    const captchaImg = document.querySelector('.captcha-img');
    captchaImg.src = '/captcha?' + new Date().getTime();
}

let timer = null;
const COUNTDOWN_TIME = 60;

// 开始倒计时
function startCountdown(button) {
    let countdown = COUNTDOWN_TIME;
    button.disabled = true;
    button.textContent = `${countdown}秒后重试`;

    timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(timer);
            button.disabled = false;
            button.textContent = '获取验证码';
        } else {
            button.textContent = `${countdown}秒后重试`;
        }
    }, 1000);
}

// 发送短信验证码
function sendSmsCode() {
    const phone = document.getElementById('phone').value;
    // const imageCaptcha = document.getElementById('imageCaptcha').value;
    const sendSmsUrl = document.getElementById('sendSmsUrl').value;

    // 简单的手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号');
        return;
    }
    
    // if (!imageCaptcha) {
    //     alert('请输入图片验证码');
    //     return;
    // }

    // 获取按钮元素
    const button = document.querySelector('.suffix-btn');
    
    const data = {
        phone:phone,
        // verify:imageCaptcha,
        gid:gid,
        cid:cid
    };
    // 这里添加发送短信验证码的逻辑
    // 假设这里是发送验证码的API调用
    $.post(sendSmsUrl,data,function(info){
        if(info.code==0) {
            layer.msg(info.msg,{time:2000});
            refreshCaptcha();
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            // 发送成功后开始倒计时
            startCountdown(button);
        }else{
            // 其他错误
            layer.msg(info.msg || '发送失败，请重试', {time: 2000});
        }
    })

}

// 登录
function login(type) {
    if (type === 'phone') {
        const phone = document.getElementById('phone').value;
        const smsCode = document.getElementById('smsCaptcha').value;
        const loginUrl = document.getElementById('loginPhoneUrl').value;
        const token = '';
        // 手机号登录逻辑
        const data = {
            phone:phone,
            code:smsCode,
            gid:gid,
            cid:cid
        };
        // 这里添加注册API调用
        $.post(loginUrl,data,function(info){
            console.log(info);
            if(info.code!=1) {
                layer.msg(info.msg,{time:2000});
                return false;
            }
            token = info.data.token;
            layer.msg(info.msg,{time:2000});
            //登录成功后，根据返回的info.game_url 重新加载iframe id="game-frame" 
            document.getElementById('game-frame').src = info.data.game_url;
            //缓存token
            // 登录成功后调用
            showFloatBall();
            hideLoginModal();
            document.getElementById('game-frame').style.display = 'block';
        })
        // 登录成功后保存手机号
        savePhoneToLocal(phone);
    } else {
        // const account = document.getElementById('account').value;
        // const password = document.getElementById('password').value;
        // const loginUrl = document.getElementById('loginAccountUrl').value;
        // 账号登录逻辑
        const data = {
            // account:account,
            // password:password,
            // gid:gid,
            // cid:cid
        };
        // 这里添加注册API调用
        // $.post(loginUrl,data,function(info){
        //     console.log(info.code);
        //     if(info.code!=1) {
        //         layer.msg(info.msg,{time:2000});
        //         return false;
        //     }
        //     token = info.data.token;
        //     layer.msg(info.msg,{time:2000});
        //     //登录成功后，根据返回的info.game_url 重新加载iframe id="game-frame" 
        //     document.getElementById('game-frame').src = info.data.game_url;
        //     //缓存token
        //     // 登录成功后调用
        //     showFloatBall();
        //     hideLoginModal();
        //     document.getElementById('game-frame').style.display = 'block';
        // })
        // 登录成功后保存账号和密码
        // saveAccountToLocal(account, password);
    }
}

// 刷新注册页面的图片验证码
function refreshRegisterCaptcha() {
    const captchaImg = document.querySelector('#registerModal .captcha-img');
    captchaImg.src = '/captcha?' + new Date().getTime();
}

// 注册功能
function register() {
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const imageCaptcha = document.getElementById('registerImageCaptcha').value;
    const registerUrl = document.getElementById('registerUrl').value;
    const registerType = document.getElementById('registerType').value;


    // 表单验证
    if (!username || !password || !confirmPassword || !imageCaptcha) {
        layer.msg('请填写完整信息');
        return;
    }

    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }
    console.log(username,password,confirmPassword,imageCaptcha,gid,cid,registerUrl);
    const data = {
        account:username,
        password:password,
        verify:imageCaptcha,
        type:registerType,
        gid:gid,
        cid:cid
    };
    // 这里添加注册API调用
    $.post(registerUrl,data,function(info){
        if(info.code!=1){
            layer.msg(info.msg,{time:2000});return;
        }
        layer.msg(info.msg,{time:2000});
    })
    // 注册成功后关闭注册弹窗，显示登录弹窗
    hideRegisterModal();
}

// 页面加载完成后检查登录状态
window.onload = function() {
    const gameFrame = document.getElementById('game-frame');
    const loading = document.querySelector('.loading');
    
    if (checkLoginStatus() && cid <= 0) {
        gameFrame.style.display = 'block';
        showFloatBall();
        gameFrame.onload = function() {
            loading.style.display = 'none';
        };
    } else {
        showLoginModal();
        // 默认显示账号登录
        switchToAccountLogin();
    }

    // 初始化账号和手机号选择框
    const accountInput = document.getElementById('account');
    const phoneInput = document.getElementById('phone');
    const accountOptions = document.getElementById('accountOptions');
    const phoneOptions = document.getElementById('phoneOptions');

    accountInput.addEventListener('focus', () => {
        loadCachedAccounts();
        accountOptions.style.display = 'block';
    });

    phoneInput.addEventListener('focus', () => {
        loadCachedPhones();
        phoneOptions.style.display = 'block';
    });

    // 点击其他地方关闭下拉框
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.account-select')) {
            accountOptions.style.display = 'none';
        }
        if (!e.target.closest('.phone-select')) {
            phoneOptions.style.display = 'none';
        }
    });
};

// 页面切换时清除定时器
function switchToAccountLogin() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
    document.getElementById('phoneLoginForm').style.display = 'none';
    document.getElementById('accountLoginForm').style.display = 'block';
}

// 页面卸载时清除定时器
window.onunload = function() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
};

// 显示重置密码弹窗
function showResetPasswordModal() {
    document.getElementById('resetPasswordModal').style.display = 'block';
    document.getElementById('loginModal').style.display = 'none';
}

// 隐藏重置密码弹窗
function hideResetPasswordModal() {
    document.getElementById('resetPasswordModal').style.display = 'none';
    document.getElementById('loginModal').style.display = 'block';
}

// 刷新重置密码页面的图片验证码
function refreshResetCaptcha() {
    const captchaImg = document.querySelector('#resetPasswordModal .captcha-img');
    captchaImg.src = '/captcha?' + new Date().getTime();
}

// 发送重置密码短信验证码
function sendResetSmsCode() {
    const phone = document.getElementById('resetPhone').value;
    // const imageCaptcha = document.getElementById('resetImageCaptcha').value;
    const url = "{:url('/index/login/sendSms')}";
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号');
        return;
    }
    
    // if (!imageCaptcha) {
    //     alert('请输入图片验证码');
    //     return;
    // }
    const data = {
        phone:phone,
        type:1,
        // verify:imageCaptcha,
        gid:gid,
        cid:cid,
    };

    $.post(url,data,function(info){
        if(info.code==0) {
            layer.msg(info.msg,{time:2000});
            refreshCaptcha();
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            // 发送成功后开始倒计时
            startCountdown(button);
        }else{
            // 其他错误
            layer.msg(info.msg || '发送失败，请重试', {time: 2000});
        }
    })
    const button = document.querySelector('#resetPasswordModal .suffix-btn');
    startCountdown(button);
}

// 重置密码功能
function resetPassword() {
    const phone = document.getElementById('resetPhone').value;
    const smsCode = document.getElementById('resetSmsCode').value;
    const password = document.getElementById('resetPassword').value;
    const confirmPassword = document.getElementById('resetConfirmPassword').value;
    const url = "{:url('/index/player/forgetPassword')}";
    // 表单验证
    if (!phone || !smsCode || !password || !confirmPassword) {
        alert('请填写完整信息');
        return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号');
        return;
    }

    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }

    
    // 这里添加重置密码API调用
    const data = {
        phone:phone,
        code: smsCode,
        password:password,
        uid:uid,
        // verify:imageCaptcha,
        gid:gid,
        cid:cid
    };
    $.post(url,data,function(info){
        if(info.code==0) {
            layer.msg('密码重置成功',{time:2000});
            refreshCaptcha();
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            // 发送成功后开始倒计时
            startCountdown(button);
        }else{
            // 其他错误
            layer.msg(info.msg || '发送失败，请重试', {time: 2000});
        }
    })

    hideResetPasswordModal();
}

// 账号缓存相关函数
const CACHE_DURATION = 30 * 24 * 60 * 60 * 1000; // 30天的毫秒数

// 保存账号信息到本地存储
function saveAccountToLocal(account, password) {
    let accounts = JSON.parse(localStorage.getItem('cachedAccounts') || '[]');
    const now = new Date().getTime();
    
    // 检查是否已存在该账号
    const existingIndex = accounts.findIndex(a => a.account === account);
    if (existingIndex !== -1) {
        accounts.splice(existingIndex, 1);
    }
    
    // 添加新账号到开头
    accounts.unshift({
        account,
        password,
        timestamp: now
    });
    
    // 清理过期账号
    accounts = accounts.filter(a => (now - a.timestamp) <= CACHE_DURATION);
    
    localStorage.setItem('cachedAccounts', JSON.stringify(accounts));
}

// 保存手机号到本地存储
function savePhoneToLocal(phone) {
    let phones = JSON.parse(localStorage.getItem('cachedPhones') || '[]');
    const now = new Date().getTime();
    
    // 检查是否已存在该手机号
    const existingIndex = phones.findIndex(p => p.phone === phone);
    if (existingIndex !== -1) {
        phones.splice(existingIndex, 1);
    }
    
    // 添加新手机号到开头
    phones.unshift({
        phone,
        timestamp: now
    });
    
    // 清理过期手机号
    phones = phones.filter(p => (now - p.timestamp) <= CACHE_DURATION);
    
    localStorage.setItem('cachedPhones', JSON.stringify(phones));
}

// 加载缓存的账号
function loadCachedAccounts() {
    const accounts = JSON.parse(localStorage.getItem('cachedAccounts') || '[]');
    const accountOptions = document.getElementById('accountOptions');
    accountOptions.innerHTML = '';
    
    accounts.forEach(acc => {
        const option = document.createElement('div');
        option.className = 'account-option';
        option.textContent = acc.account;
        option.onclick = () => selectAccount(acc.account, acc.password);
        accountOptions.appendChild(option);
    });
}

// 加载缓存的手机号
function loadCachedPhones() {
    const phones = JSON.parse(localStorage.getItem('cachedPhones') || '[]');
    const phoneOptions = document.getElementById('phoneOptions');
    phoneOptions.innerHTML = '';
    
    phones.forEach(p => {
        const option = document.createElement('div');
        option.className = 'phone-option';
        option.textContent = p.phone;
        option.onclick = () => selectPhone(p.phone);
        phoneOptions.appendChild(option);
    });
}

// 选择账号
function selectAccount(account, password) {
    document.getElementById('account').value = account;
    document.getElementById('password').value = password;
    document.getElementById('accountOptions').style.display = 'none';
    
    // 更新选中状态样式
    const options = document.querySelectorAll('.account-option');
    options.forEach(opt => {
        opt.classList.toggle('selected', opt.textContent === account);
    });
}

// 选择手机号
function selectPhone(phone) {
    document.getElementById('phone').value = phone;
    document.getElementById('phoneOptions').style.display = 'none';
    
    // 更新选中状态样式
    const options = document.querySelectorAll('.phone-option');
    options.forEach(opt => {
        opt.classList.toggle('selected', opt.textContent === phone);
    });
}

// 悬浮球点击事件
document.getElementById('floatBall').addEventListener('click', function() {
    this.classList.add('active');
    showAccountCenter();
});

// 显示账户中心
function showAccountCenter() {
    document.getElementById('accountCenter').style.display = 'flex';
}

// 隐藏账户中心
function hideAccountCenter() {
    document.getElementById('accountCenter').style.display = 'none';
    document.getElementById('floatBall').classList.remove('active');
}

// 切换账号
function switchAccount() {
    hideAccountCenter();
    showLoginModal();
}

// 处理修改密码按钮点击
function handleResetPassword() {
    hideAccountCenter(); // 先关闭账户中心
    showChangePasswordModal(); // 显示修改密码窗口
}

// 显示修改密码弹窗
function showChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'block';
}

// 隐藏修改密码弹窗
function hideChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'none';
}

// 修改密码
function changePassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmNewPassword = document.getElementById('confirmNewPassword').value;

    // 表单验证
    if (!oldPassword || !newPassword || !confirmNewPassword) {
        layer.msg('请填写完整信息');
        return;
    }

    if (newPassword !== confirmNewPassword) {
        layer.msg('两次输入的新密码不一致');
        return;
    }

    // 这里添加修改密码API调用
    const data = {
        old_password: oldPassword,
        password: newPassword,
        uid: uid,
        gid: gid,
        cid: cid
    };

    $.post('/index/player/changePassword', data, function(info) {
        if (info.code != 1) {
            layer.msg(info.msg, {time: 2000});
            return;
        }
        layer.msg('密码修改成功', {time: 2000});
        hideChangePasswordModal();
    });
}

// 复制QQ号码
function copyQQ() {
    const qq = "823039764";
    const textarea = document.createElement('textarea');
    textarea.value = qq;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    layer.msg('QQ号已复制到剪贴板', {time: 2000});
}

// 处理切换账号
function handleSwitchAccount() {
    // 这里添加修改密码API调用
    const data = {
        gid: gid,
        cid: cid
    };
    // 先调用退出登录接口
    $.post('/index/login/logout', data, function(info) {
        if(info.code == 1) {
            layer.msg('退出成功', {time: 2000});
            // 关闭账户中心
            hideAccountCenter();
            // 显示登录窗口
            showLoginModal();
            // 默认显示账号登录
            switchToAccountLogin();
            // 隐藏游戏框架
            document.getElementById('game-frame').style.display = 'none';
        } else {
            layer.msg(info.msg || '退出失败', {time: 2000});
        }
    });
}

// 支付相关函数
let selectedPaymentMethod = null;

// 显示支付弹窗
function showPaymentModal(amount) {
    document.getElementById('paymentModal').style.display = 'block';
    document.getElementById('paymentAmount').textContent = amount.toFixed(2);
    selectedPaymentMethod = null;
    updatePaymentButton();
}

// 隐藏支付弹窗
function hidePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
}

// 选择支付方式
function selectPaymentMethod(method) {
    selectedPaymentMethod = method;
    const methods = document.querySelectorAll('.payment-method');
    methods.forEach(m => m.classList.remove('selected'));
    document.querySelector(`.payment-method[onclick*="${method}"]`).classList.add('selected');
    updatePaymentButton();
}

// 更新支付按钮状态
function updatePaymentButton() {
    const button = document.querySelector('.btn-payment');
    button.disabled = !selectedPaymentMethod;
}

// 确认支付
function confirmPayment() {
    if (!selectedPaymentMethod) {
        layer.msg('请选择支付方式', {time: 2000});
        return;
    }

    const amount = parseFloat(document.getElementById('paymentAmount').textContent);
    const data = {
        amount: amount,
        payment_method: selectedPaymentMethod,
        gid: gid,
        cid: cid,
        uid: uid
    };

    // 这里添加支付API调用
    $.post('/index/payment/create', data, function(info) {
        if (info.code == 1) {
            // 根据支付方式跳转到相应的支付页面
            if (selectedPaymentMethod === 'wechat') {
                // 微信支付
                window.location.href = info.data.pay_url;
            } else if (selectedPaymentMethod === 'alipay') {
                // 支付宝支付
                window.location.href = info.data.pay_url;
            }
        } else {
            layer.msg(info.msg || '支付失败，请重试', {time: 2000});
        }
    });
}